#!/usr/bin/env python
# -*-coding: utf8 -*-
'''
# created by: iori
# created on: Thu 12 Dec 2013 11:26:03 AM CST
'''


import unittest
import time, re, os, hashlib
import json
import requests
import bencode
def current_timestamp():
    return (int(time.time()))

def md5(s):
    ''' 计算文件或串的md5值 '''
    return hashlib.md5(s).hexdigest().lower()

def sha1(s):
    '''
    @description 计算文件或串的sha1
    @params s: 可为一个串或者文件路径
    @return 十六进制的sha1值
    '''
    hasher = hashlib.sha1()
    if os.path.isfile(s):
        BLOCKSIZE = 65536
        with open(s, 'rb') as fp:
            buff = fp.read(BLOCKSIZE)
            while len(buff)>0:
                hasher.update(buff)
                buff = fp.read(BLOCKSIZE)
    else:
        hasher.update(s)
    return hasher.hexdigest()

def magnet_hash(data):
    ''' 计算一个种子文件的磁力链链接'''
    if  hasattr(data, 'read'):
        data = data.read()
    elif len(data)<1024 and os.path.isfile(data):
        with open(data, 'rb') as fp:
            data = fp.read()
    meta = bencode.bdecode(data)
    hash_body = bencode.bencode(meta['info'])
    digest = hashlib.sha1(hash_body).hexdigest()
    return digest


